package cn.edu.nks.dormitory.home.dbimpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import cn.edu.nks.dormitory.home.db.IDBService;
import cn.edu.nks.dormitory.model.ModuleInfo;
import cn.edu.nks.dormitory.model.ModulePower;
import cn.edu.nks.util.DBConnectProvider;

public class DBService implements IDBService{
	private static Logger logger = Logger.getLogger(DBService.class);
	
	public ModuleInfo getModuleInfoByModuleId(int moduleId) {
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		ModuleInfo item = null;
		
		con = DBConnectProvider.getConnection();
		if(null == con){
			logger.warn("get connect faild");
			return null;
		}
		StringBuffer sql = new StringBuffer();
		sql.append("select * from moduleinfo where moduleid = ?");
		try {
			stmt = con.prepareStatement(sql.toString());
			stmt.setInt(1, moduleId);
			rs = stmt.executeQuery();
			if(rs.next()){
				item = new ModuleInfo();
				item.setModuleId(rs.getInt("moduleid"));
				item.setModuleName(rs.getString("modulename"));
				item.setPath(rs.getString("path"));
			}
		} catch (SQLException e) {
			logger.warn(String.format("getModuleInfoByModuleId is error :%s", e));
		}
		DBConnectProvider.freeConnection(con);
		
		return item;
	}

	public List<ModulePower> getModulePowerByRoleId(int roleId) {
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		List<ModulePower> items = new ArrayList<ModulePower>();
		
		con = DBConnectProvider.getConnection();
		if(null == con){
			logger.warn("get connect faild");
			return null;
		}
		StringBuffer sql = new StringBuffer();
		sql.append("select * from modulepower where roleid = ?");
		try {
			stmt = con.prepareStatement(sql.toString());
			stmt.setInt(1, roleId);
			rs = stmt.executeQuery();
			while(rs.next()){
				ModulePower item = new ModulePower();
				item.setModuleId(rs.getInt("moduleid"));
				item.setRoleId(rs.getInt("roleid"));
				items.add(item);
			}
		} catch (SQLException e) {
			logger.warn(String.format("getModulePowerByRoleId is error :%s", e));
		}
		DBConnectProvider.freeConnection(con);
		
		return items;
	}

}
